const Koa = require('koa')
const app = new Koa()
const cors = require('koa-cors')
const static = require('koa-static')
const bodyparser = require('koa-bodyparser')
const PORT = 8080
const path = require('path')
const router = require('./routes')

// 错误处理中间件
app.use(async (ctx,next) => {
    try{
        await next()
    }catch (e){
        console.log(`server err: ${e}`)
        ctx.status = 500;
        ctx.body = {
            code: 500,
            msg: 'server error!'
        }
    }
})

// 设置静态资源文件
app.use(static(path.join(__dirname,'/public')))

// 设置cors跨域
app.use(cors())

// 解析post请求数据
app.use(bodyparser())
 
// 启用总路由
app.use(router.routes(),router.allowedMethods())

// 开启服务
app.listen(PORT,() => {
    console.log(`smartisan server is running on http://127.0.0.1:${PORT}`);
})